package com.sisyphus.spinach.network.task;



import com.sisyphus.spinach.core.INetPageTask;
import com.sisyphus.spinach.core.model.IPageResponse;
import com.sisyphus.spinach.core.model.IResponse;
import com.sisyphus.spinach.network.ResponsePageObserver;
import com.sisyphus.spinach.network.utils.RxUtil;

import io.reactivex.rxjava3.core.Observable;

/**
 * 分页任务
 */
public abstract class NetPageTask<T>
        extends NetLifecycleTask<T, INetPageTask.View<T>>
        implements INetPageTask.Presenter<T, INetPageTask.View<T>> {

    private int mPage;

    @Override
    public void refresh() {
        mPage = 1;

        try {

            execute(mPage).compose(RxUtil.transformer()).subscribe(new ResponsePageObserver<>(mPage, mView, this));
        } catch (Exception e) {

            mView.complete();
            mView.failure(e);
        }
    }

    @Override
    public void loadMore() {
        mPage = mPage + 1;

        try {

            execute(mPage).compose(RxUtil.transformer()).subscribe(new ResponsePageObserver<>(mPage, mView, this));
        } catch (Exception e) {

            mView.complete();
            mView.failure(e);
        }
    }

    @Override
    public void execute() {
        refresh();
    }

    public abstract Observable<? extends IResponse<? extends IPageResponse<T>>> execute(int page);

}
